package cn.didi.feidi.androidorder.fragment.personal;

import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.adapter.SearchWaterStoreAdapter;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.assembly.PersonReturnDepositBucketInputPopupWindow;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.WaterStore;

import static android.content.ContentValues.TAG;

/**
 * Created by dugu on 2017/8/25.
 */

public class PersonReturnDepositFragment extends FeidiBaseFragment {

    private boolean searching;

    private PersonReturnDepositBucketInputPopupWindow menuWindow;

    private int amount = 0;
    private int returnBucketNum = 0;

    private ListView lvWaterStores;
    private SearchWaterStoreAdapter searchWaterStoreAdapter;
    private List<WaterStore> waterStoreList = new ArrayList<WaterStore>();

    private int pageSize = 12;
    private int pageNum = 1;
    private int blankBucket;

    private boolean isMore = true;

    private WaterStore waterStore = new WaterStore();

    private String searchKey = "";

    private TextView tvSearch;
    private EditText etInput;
    private View vback;
    private View vClear;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonReturnDepositFragment newInstance(Bundle bundle) {
        PersonReturnDepositFragment fragment = new PersonReturnDepositFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        blankBucket = getActivity().getIntent().getIntExtra("blankBucket", -1);
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_return_deposit, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        actionBarSetting();

        tvSearch = (TextView) rootView.findViewById(R.id.search_water_market_search_tv);
        etInput = (EditText) rootView.findViewById(R.id.search_water_market_search_et);
        vback = rootView.findViewById(R.id.search_water_market_back_fl);
        vClear = rootView.findViewById(R.id.search_water_market_clear_text_iv);

        lvWaterStores = (ListView) rootView.findViewById(R.id.search_water_store_list);

        searchWaterStoreAdapter = new SearchWaterStoreAdapter(getContext(), R.layout.item_search_water_store_view, waterStoreList);
        lvWaterStores.setAdapter(searchWaterStoreAdapter);

        //  : 2017/8/31
//        rootView.findViewById(R.id.search_water_market_search_tv).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                menuWindow = new PersonReturnDepositBucketInputPopupWindow(getActivity(), new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        searchKey = inputWaterMarket.getText().toString().trim();
//                        pageNum = 1;
//                        loadFirstData();
//                    }
//                });
//                menuWindow.showAtLocation(getView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
//                setOtherPlaceDark();
//            }
//        });
    }


    @Override
    protected void initData() {
        amount = (int) Math.rint(UserManager.getDeposit() / 50);
        loadFirstData();
    }

    @Override
    protected void addListener() {
        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchKey = etInput.getText().toString().trim();
                pageNum = 1;
                loadFirstData();
            }
        });

        lvWaterStores.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == waterStoreList.size() - 1 && isMore) {
                    loadMoreData();
                } else {
                    WaterStore chooseWaterStore = waterStoreList.get(position);
                    setOtherPlaceDark(chooseWaterStore);
                }
            }
        });

        vback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.finish();
            }
        });

        vClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etInput.setText("");
            }
        });

    }


    public void actionBarSetting() {
        getFeidiActionBar().setVisibility(View.GONE);
    }

    //    设置popupWindow 弹出时界面其它部分变透明
    private void setOtherPlaceDark(final WaterStore chooseWaterStore) {
        menuWindow = new PersonReturnDepositBucketInputPopupWindow(getActivity(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = menuWindow.getBucketNum();
                if (str == null || "".equals(str)) {
                    makeToast("空桶不能为空");
                    return;
                }
                try {
                    returnBucketNum = Integer.parseInt(str);
                    Toast.makeText(mActivity, "" + returnBucketNum, Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onClick: " + returnBucketNum);

                    if (returnBucketNum > blankBucket) {
                        makeToast("空桶数不正确");
                        return;
                    }
                    if (returnBucketNum == 0) {
                        makeToast("不能为0");
                        return;
                    }
                } catch (Exception ex) {
                    makeToast("输入不正确");
                    return;
                }


                showConfirmDialog(chooseWaterStore);
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuWindow.dismiss();
            }
        }).setWaterStoreName(chooseWaterStore.getName());
        menuWindow.showAtLocation(getView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
        //当弹出Popupwindow时，背景变半透明
        params.alpha = 0.7f;
        getActivity().getWindow().setAttributes(params);
        //设置Popupwindow关闭监听，当Popupwindow关闭，背景恢复1f
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
                params.alpha = 1f;
                getActivity().getWindow().setAttributes(params);
            }
        });
    }

    private void showConfirmDialog(final WaterStore chooseWaterStore) {
        Log.d(TAG, "chooseWaterStore " + chooseWaterStore.getWaterStoreId());
        new CommomDialog(getContext(), R.style.dialog, "确认要退还空桶？", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    //  执行押金退还申请操作
                    submitReturnDeposit(chooseWaterStore.getWaterStoreId());
                    dialog.dismiss();
                } else {
                    dialog.dismiss();
                    getActivity().finish();
                    makeToast("已取消退还申请");
                }
            }
        }, false, true).setPositiveButton("确认退还", "#999999").setNegativeButton("再想想", "#999999").show();
    }


    /**
     * 退还押金请求
     *
     * @param waterStoreId
     */
    private void submitReturnDeposit(String waterStoreId) {
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("waterStoreId", waterStoreId);
        params.put("amount", String.valueOf(returnBucketNum));

        executeRequest(new AppActionRequest<String>(Api.SUBMIT_DEPOSIT_ORDER, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                showEndDialog();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                makeToast("申请失败");
            }
        }));
    }

    private void showEndDialog() {
        new CommomDialog(getContext(), R.style.dialog, "退还押金订单已提交，\n" +
                "请带空桶到该水店退还", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    dialog.dismiss();
                    getActivity().finish();
                }
            }
        }, true, true).setPositiveButton("确定").show();

    }

    private void loadFirstData() {

        if (returnBucketNum == 0) {
            makeToast("不能为 0 ");
            return;
        }
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("searchKey", searchKey);
        params.put("longitude", String.valueOf(OrderApplication.getLongitude()));
        params.put("latitude", String.valueOf(OrderApplication.getLatitude()));
        params.put("pageNum", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(pageSize));

        executeRequest(new AppActionRequest<List<WaterStore>>(Api.GET_WATER_STORE_PAGE, params,
                new TypeToken<ApiResponse<List<WaterStore>>>() {
                }.getType(), new ActionCallbackListener<List<WaterStore>>() {
            @Override
            public void onSuccess(String message, List<WaterStore> data) {
                waterStore.setName("");
                waterStore.setAddress("");
                //清除数据并加载
                waterStoreList.clear();
                if (data != null && !data.isEmpty()) {
                    if (data.size() == pageSize) {
                        waterStoreList.addAll(data);
                        waterStoreList.add(waterStore);
                        searchWaterStoreAdapter.notifyDataSetChanged();
                    } else {
                        waterStoreList.addAll(data);
                        waterStoreList.add(waterStore);
                        searchWaterStoreAdapter.setMore(false);
                        searchWaterStoreAdapter.notifyDataSetChanged();
                    }
                } else {
                    isMore = false;
                    waterStoreList.add(waterStore);
                    searchWaterStoreAdapter.setMore(false);
                    searchWaterStoreAdapter.notifyDataSetChanged();
                    Log.d(TAG, message);
                }
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                switch (errorEvent) {
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }

    private void loadMoreData() {
        Map<String, String> params = new HashMap<>();
        pageNum++;
        searchWaterStoreAdapter.setLoadText("正在加载");
        searchWaterStoreAdapter.notifyDataSetChanged();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("searchKey", searchKey);
        params.put("longitude", String.valueOf(OrderApplication.getLongitude()));
        params.put("latitude", String.valueOf(OrderApplication.getLatitude()));
        params.put("pageNum", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(pageSize));

        executeRequest(new AppActionRequest<List<WaterStore>>(Api.GET_WATER_STORE_PAGE, params,
                new TypeToken<ApiResponse<List<WaterStore>>>() {
                }.getType(), new ActionCallbackListener<List<WaterStore>>() {
            @Override
            public void onSuccess(String message, List<WaterStore> data) {
                if (data != null && !data.isEmpty()) {
                    if (data.size() == pageSize) {
                        waterStoreList.remove(waterStore);
                        waterStoreList.addAll(data);
                        waterStoreList.add(waterStore);
                        searchWaterStoreAdapter.setLoadText("加载更多");
                        searchWaterStoreAdapter.notifyDataSetChanged();
                    } else {
                        isMore = false;
                        waterStoreList.remove(waterStore);
                        waterStoreList.addAll(data);
                        waterStoreList.add(waterStore);
                        searchWaterStoreAdapter.setMore(false);
                        searchWaterStoreAdapter.setLoadText("没有更多数据了");
                        searchWaterStoreAdapter.notifyDataSetChanged();
                    }
                } else {
                    isMore = false;
                    searchWaterStoreAdapter.setMore(false);
                    searchWaterStoreAdapter.setLoadText("没有更多数据了");
                    searchWaterStoreAdapter.notifyDataSetChanged();
                    makeToast("没有更多数据了");
                    Log.d(TAG, message);
                }
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                switch (errorEvent) {
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }
}
